//
//  ZYDeviceViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/19.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDeviceViewModel.h"
#import "AFNetWorkUtils.h"
#import "ZYDevice.h"
#import "HFSmartLink.h"

@interface ZYDeviceViewModel()

@property(nonatomic,copy) NSString *ip;
/**
 设备连接
 */
@property(nonatomic,strong) RACCommand *deviceConnectCommand;
/**
 设备修改
 */
@property(nonatomic,strong) RACCommand *deviceModifyCommand;

/**
 获取设备socket ip地址
 */
@property(nonatomic,strong) RACCommand *deviceSocketCommand;

/**
 设备列表
 */
@property(nonatomic,strong) RACCommand *deviceListCommand;

/**
 设备删除
 */
@property(nonatomic,strong) RACCommand *deleteCommand;

/**
 设备状态改变 离家模式和在家模式
 */
@property(nonatomic,strong) RACCommand *statusChangeCommand;
@end

@implementation ZYDeviceViewModel

-(RACCommand *)deviceConnectCommand{
    if(!_deviceConnectCommand){
        @weakify(self);
        _deviceConnectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [_smtlk startWithKey:self.password processblock:^(NSInteger process) {
                    NSLog(@"process %ld",process);
                } successBlock:^(HFSmartLinkDeviceInfo *dev) {
                    NSLog(@"deviceinfo mac = %@; ip = %@",dev.mac,dev.ip);
                    NSMutableString *_macstr = [NSMutableString stringWithString:[dev.mac lowercaseString]];
//                    [_macstr insertString:@":" atIndex:2];
//                    [_macstr insertString:@":" atIndex:5];
//                    [_macstr insertString:@":" atIndex:8];
//                    [_macstr insertString:@":" atIndex:11];
//                    [_macstr insertString:@":" atIndex:14];
                    
                    self.mac = _macstr;
                    self.ip = dev.ip;
                    //验证设备id
                    [self checkDevice:subscriber];
                    //关闭连接
                    [_smtlk closeWithBlock:^(NSString *closeMsg, BOOL isOK) {
                        if(!isOK){
                            NSLog(@"%@",closeMsg);
                        }
                    }];
                    
                } failBlock:^(NSString *failmsg) {
                    NSLog(@"error %@",failmsg);
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_DEVICE_CONNECT_FAIL]]];
                    [subscriber sendCompleted];
                } endBlock:^(NSDictionary *deviceDic) {
                    NSLog(@"endBlock");
                    //[HUDManager hide];
//                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _deviceConnectCommand;
}

-(RACCommand *)deviceModifyCommand{
    if(!_deviceModifyCommand){
        @weakify(self);
        _deviceModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doModifyDeviceBySubscriber:subscriber];
                return nil;
            }];
        }];
    }
    return _deviceModifyCommand;
}

-(RACCommand *)deviceSocketCommand{
    if(!_deviceSocketCommand){
        @weakify(self);
        _deviceSocketCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_SOCKET_IP_URL];
                NSDictionary *params;
                params = @{@"macAddress":self.mac};
                [[AFNetWorkUtils racGETWithURL:url params:params] subscribeNext:^(id x) {
                    NSString *socketIp = [x objectForKey:@"result"];
                    [subscriber sendNext:socketIp];
                    [subscriber sendCompleted];
                } error:^(NSError *error) {
                    [subscriber sendError:error];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _deviceSocketCommand;
}

-(RACCommand *)deviceListCommand{
    if(!_deviceListCommand){
        _deviceListCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            NSString *token = [ZYConfig loginToken];
            NSString *houseId = [ZYConfig houseId];
            if(NULLString(houseId)){
                return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:@""]];
                    [subscriber sendCompleted];
                    return nil;
                }];
            }
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_LIST_URL];
            NSDictionary *params;
            params = @{@"ssid":token,@"houseId":houseId};
            
            return [[AFNetWorkUtils racGETWithURL:url params:params] map:^id(id value) {
                NSDictionary *data = value;
                NSDictionary *result = [data objectForKey:@"result"];
                NSMutableArray *deviceArray = [NSMutableArray array];
                NSArray *kidsRoomJson = [result objectForKey:@"kidsRoom"];
                NSArray *livingRoomJson = [result objectForKey:@"livingRoom"];
                NSArray *bedroomJson = [result objectForKey:@"bedroom"];
                NSArray *kidsRoom = [NSArray modelArrayWithClass:[ZYDevice class] json:kidsRoomJson];
                NSArray *livingRoom = [NSArray modelArrayWithClass:[ZYDevice class] json:livingRoomJson];
                NSArray *bedroom = [NSArray modelArrayWithClass:[ZYDevice class] json:bedroomJson];
                for (ZYDevice *device in kidsRoom) {
                    device.roomType = ZYHomeRoomTypeChildrenRoom;
                }
                for (ZYDevice *device in livingRoom) {
                    device.roomType = ZYHomeRoomTypeLivingRoom;
                }
                for (ZYDevice *device in bedroom) {
                    device.roomType = ZYHomeRoomTypeBedroom;
                }
                [deviceArray addObjectsFromArray:kidsRoom];
                [deviceArray addObjectsFromArray:livingRoom];
                [deviceArray addObjectsFromArray:bedroom];
                return deviceArray;
            }];
        }];
    }
    return _deviceListCommand;
}

-(void)doModifyDeviceBySubscriber:(id<RACSubscriber>)subscriber{
    //校验数据
    BOOL success = [self checkData:subscriber];
    if(!success){
        return;
    }
    NSString *url = @"";
    if(_isModify){
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_MODIFY_URL];
    }else{
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_ADD_URL];
    }
    NSDictionary *params;
    NSString *token = [ZYConfig loginToken];
    NSInteger deviceType = 0;
    switch (self.deviceType) {
        case ZYDeviceTypeAirConditioning:
            deviceType = 1;
            break;
        case ZYDeviceTypeRadiantFloorHeating:
            deviceType = 2;
            break;
        case ZYDeviceTypeVentilationSystem:
            deviceType = 3;
            break;
    }
    NSInteger roomType = 0;
    switch (self.roomType) {
        case ZYHomeRoomTypeBedroom:
            roomType = 0;
            break;
        case ZYHomeRoomTypeLivingRoom:
            roomType = 2;
            break;
        case ZYHomeRoomTypeChildrenRoom:
            roomType = 1;
            break;
    }
    params = @{@"ssid":token,@"deviceName":self.name,@"macAddress":self.mac,@"deviceModel":self.model,
               @"deviceType":[NSNumber numberWithInteger:deviceType],@"houseId":[NSNumber numberWithInteger:self.houseId],@"roomType":[NSNumber numberWithInteger:roomType]
               };
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        [subscriber sendNext:x];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}

-(BOOL)checkData:(id<RACSubscriber>)subscriber{
    if(NULLString(self.name)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(self.model)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    return YES;
}

-(void)checkDevice:(id<RACSubscriber>)subscriber{
    NSString *token = [ZYConfig loginToken];
    NSString *houseId = [ZYConfig houseId];
    NSDictionary *params = @{@"macAddress":self.mac,@"deviceIp":self.ip,@"ssid":token,@"houseId":houseId};
    NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_VERIFY_URL];
    [[AFNetWorkUtils racGETWithURL:url params:params] subscribeNext:^(id x) {
        NSString *code = [x objectForKey:@"code"];
        NSDictionary *dict ;
        if([code integerValue] == 200){
            dict = @{@"mac":self.mac,@"ip":self.ip,@"success":@YES,@"is_add":@YES};
        }else{
            BOOL success = [[x objectForKey:@"success"] boolValue];
            if(success){
                dict = @{@"mac":self.mac,@"ip":self.ip,@"success":@NO,@"is_add":@YES};
            }else{
                dict = @{@"mac":self.mac,@"ip":self.ip,@"success":@NO,@"is_add":@NO};
            }
            
        }
        [subscriber sendNext:dict];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}

-(RACCommand *)deleteCommand{
    if(!_deleteCommand){
        @weakify(self);
        _deleteCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @strongify(self);
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_DEVICE_DELETE_URL];
            NSDictionary *params;
            params = @{@"macAddress":self.mac,@"ssid":[ZYConfig loginToken]};
            return [AFNetWorkUtils racGETWithURL:url params:params];
        }];
    }
    return _deleteCommand;
}

-(RACCommand *)statusChangeCommand{
    if(!_statusChangeCommand){
        @weakify(self);
        _statusChangeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @strongify(self);
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOME_STATUS_CHANGE_URL];
            NSDictionary *params;
            params = @{@"ssid":[ZYConfig loginToken],@"houseId":[NSNumber numberWithInteger:self.houseId],@"isUserIn":input};
            return [AFNetWorkUtils racGETWithURL:url params:params];
        }];
    }
    return _statusChangeCommand;
}

@end
